﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SMS.Common;
using Wicresoft.SMS.Data;

namespace Wicresoft.SMS.Gateway.Host
{
    class QueryEmailTask : Task
    {
        protected IServiceConfigProvider _configProvider;
        protected IEmailDataAccess _emaildataaccess;
        protected IExchangeServerInfo _esinfo;

        public QueryEmailTask(IServiceConfigProvider configProvider, IEmailDataAccess emaildataaccess, IExchangeServerInfo esinfo)
        {
            _configProvider = configProvider;
            _emaildataaccess = emaildataaccess;
            _esinfo = esinfo;
        }

        protected override void ExecuteCore()
        {
            while (_scanAble && _configProvider.QueryEmailTaskEnable == 1)
            {
                try
                {
                    QueryMails();
                    System.Threading.Thread.Sleep(
                        _configProvider.SendEmailTaskSpan < GlobalFactory.TaskSpanBorder ? GlobalFactory.TaskSpanBorder : _configProvider.SendEmailTaskSpan);
                }
                catch (Exception ex)
                {
                    DBLog.Exception("Wicresoft.SMS.Gateway.Host.QueryEmailTask.ExecuteCore ", ex);
                }
               
            }
        }

        private void QueryMails()
        {
            try
            {
                DBLog.Debug("Entrying QueryMails");
                List<EmailInfo> list = new List<EmailInfo>();
                //DBLog.Info(_esinfo.EQHost);
                //DBLog.Info(_esinfo.EQPort);
                //DBLog.Info(_esinfo.EQUsername);
                //DBLog.Info(_esinfo.EQPassword);
                list = MailOperation.CheckMails(_esinfo.EQHost, _esinfo.EQPort, _esinfo.EQUsername, _esinfo.EQPassword);//把未读邮件读到list中
                //DBLog.Info(list.Count.ToString());
                foreach (var item in list)
                {
                    DBLog.Info(item.From + " S:" + item.Subject + " B:" + item.Body);
                }
                _emaildataaccess.SendSMSFromEmail(list);//根据邮件的from地址找到其联系人发送短信
                DBLog.Debug("Leaving QueryMails");
            }
            catch (Exception ex)
            {
                DBLog.Exception("TASK.QueryEmailTask.QueryMails ", ex);
            }
            
        }
    }
}
